package com.sdtv.basemodule.config;

import android.app.Application;

import com.blankj.utilcode.util.LogUtils;
import com.sdtv.basemodule.http.cookie.PersistentCookieStore;
import com.sdtv.basemodule.http.interceptors.CacheInteceptor;
import com.sdtv.basemodule.http.interceptors.ExceptionInterceptor;
import com.sdtv.basemodule.http.interceptors.HeaderInteceptor;
import com.sdtv.basemodule.http.interceptors.ParamInterceptor;
import com.sdtv.basemodule.http.interceptors.SSLSocketClient;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import okhttp3.Cache;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * @ProjectName: MediunFusion
 * @Package: com.sdtv.basemodule.config
 * @ClassName: AppHttpSetting
 * @Description: HTTP请求的基本设置
 * @Author: 小郭同学
 * @CreateDate: 2019-06-20 11:16
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class AppHttpSetting {
    public long getCacheTime() {
        return cacheTime;
    }

    public void setCacheTime(long cacheTime) {
        this.cacheTime = cacheTime;
    }

    public OkHttpClient.Builder getClientBuilder() {
        return clientBuilder;
    }

    public void setClientBuilder(OkHttpClient.Builder clientBuilder) {
        this.clientBuilder = clientBuilder;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public boolean isDebug() {
        return debug;
    }

    public void setDebug(boolean debug) {
        this.debug = debug;
    }

    //设置缓存时间
    private long cacheTime;
    // 构造retrofit的Okhttpclient构造工具
    private OkHttpClient.Builder clientBuilder;
    // 请求地址
    private String url;
    // 是否开启DEBUG模式
    private boolean debug = false;

    private static final int CONNECT_TIME = 20;


    public AppHttpSetting(Builder builder) {
        this.cacheTime = builder.cacheTime;
        this.clientBuilder = builder.okHttpBuilder;
        this.url = builder.baseUrl;
        this.debug = builder.debug;
    }

    public static AppHttpSetting.Builder builder() {
        return new AppHttpSetting.Builder();
    }


    /**
     * 构造这模式
     */
    public static class Builder {
        private String baseUrl;
        private long cacheTime = 60 * 1000;
        private boolean debug = false;
        private OkHttpClient.Builder okHttpBuilder;
        Application application;
        private PersistentCookieStore cookieStore;

        // 构造器
        private Builder() {
            okHttpBuilder = RetrofitUrlManager.getInstance().with(new OkHttpClient.Builder());
            okHttpBuilder.connectTimeout(CONNECT_TIME, TimeUnit.SECONDS);
            okHttpBuilder.readTimeout(CONNECT_TIME, TimeUnit.SECONDS);
            okHttpBuilder.writeTimeout(CONNECT_TIME, TimeUnit.SECONDS);
            //网络缓存interceptor
            okHttpBuilder.addNetworkInterceptor(new CacheInteceptor());
            okHttpBuilder.sslSocketFactory(SSLSocketClient.getSSLSocketFactory());
            okHttpBuilder.hostnameVerifier(SSLSocketClient.getHostnameVerifier());//配置

        }

        public Builder with(Application application) {
            this.application = application;
            this.cookieStore = PersistentCookieStore.getInstance(application);
            okHttpBuilder.cookieJar(new CookieJar() {
                @Override
                public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
//                    LogUtils.e("====》》》saveFromResponse》》》=cookies " +
//                            "==" + cookies + " \n url :" + url);
                    if (cookies != null && cookies.size() > 0) {
                        for (Cookie item : cookies) {
                            cookieStore.add(url, item);
                        }
                    }
                }

                @Override
                public List<Cookie> loadForRequest(HttpUrl url) {
                    List<Cookie> cookies = cookieStore.get(url);
//                    LogUtils.e("====》》》loadForRequest》》》=cookies " +
//                            "==" + cookies + " \n url :" + url);
                    return cookies != null ? cookies : new ArrayList<Cookie>();
                }
            });
            return this;
        }

        /**
         * 是否需要打印网络日志 默认否
         *
         * @param isShowLog
         * @return
         */
        public AppHttpSetting.Builder setHttpLog(boolean isShowLog) {
            this.debug = isShowLog;
            if (isShowLog) {

                //                HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                //                    @Override
                //                    public void log(String message) {
                //                        try {
                //                            //HttpLoggingInterceptor 拦截的log信息为unicode字符时的解决办法
                //                            //https://blog.csdn.net/chenlove1/article/details/53337723
                //                            if (EmptyUtils.isNotEmpty(message)) {
                //                                LogUtils.d("http", unicodeToUTF_8(message));
                //                            }else {
                //                                LogUtils.d("http", message+"");
                //                            }
                //                        } catch (Exception e) {
                //                            e.printStackTrace();
                //                        }
                //                    }
                //                });
                //                httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                okHttpBuilder.addInterceptor(new HttpLoggingInterceptor());
            }
            return this;
        }

        public static String unicodeToUTF_8(String src) {
            if (null == src) {
                return null;
            }
            System.out.println("src: " + src);
            StringBuilder out = new StringBuilder();
            for (int i = 0; i < src.length(); ) {
                char c = src.charAt(i);
                if (i + 6 < src.length() && c == '\\' && src.charAt(i + 1) == 'u') {
                    String hex = src.substring(i + 2, i + 6);
                    try {
                        out.append((char) Integer.parseInt(hex, 16));
                    } catch (NumberFormatException nfe) {
                        nfe.fillInStackTrace();
                    }
                    i = i + 6;
                } else {
                    out.append(src.charAt(i));
                    ++i;
                }
            }
            return out.toString();

        }

        public AppHttpSetting.Builder setCache(boolean isNeed) {
            if (application != null) {
                final File httpCacheDirectory = new File(application.getCacheDir(), "sugarHttpCache");
                //设置缓存 10M
                int cacheSize = 10 * 1024 * 1024;
                Cache cache = new Cache(httpCacheDirectory, cacheSize);
                okHttpBuilder.cache(cache);
            }

            return this;
        }

        /**
         * 写入超时 默认20s
         *
         * @param writeTimeout
         * @return
         */
        public AppHttpSetting.Builder writeTimeout(int writeTimeout) {
            okHttpBuilder.writeTimeout(writeTimeout, TimeUnit.SECONDS);
            return this;
        }

        /**
         * 连接超时 默认20s
         *
         * @param connectTimeout
         * @return
         */
        public AppHttpSetting.Builder connectTimeout(int connectTimeout) {
            okHttpBuilder.connectTimeout(connectTimeout, TimeUnit.SECONDS);
            return this;
        }

        /**
         * 读取超时 默认20s
         *
         * @param readTimeout
         * @return
         */
        public AppHttpSetting.Builder readTimeout(int readTimeout) {
            okHttpBuilder.readTimeout(readTimeout, TimeUnit.SECONDS);
            return this;
        }

        /**
         * 主的baseUrl
         *
         * @param baseUrl
         * @return
         */
        public AppHttpSetting.Builder setBaseUrl(String baseUrl) {
            this.baseUrl = baseUrl;
            return this;
        }

        /**
         * 添加url host域名
         *
         * @param domanName
         * @param domanHost
         * @return
         */
        public AppHttpSetting.Builder putDomain(String domanName, String domanHost) {
            RetrofitUrlManager.getInstance().putDomain(domanName, domanHost);
            return this;
        }

        //设置拦截器 interceptor

        /**
         * 设置header拦截
         *
         * @param headerInterceptor
         * @return
         */
        public AppHttpSetting.Builder addHeaderInterceptor(HeaderInteceptor headerInterceptor) {
            this.okHttpBuilder.addInterceptor(headerInterceptor);
            return this;
        }

        /**
         * 添加公共的请求参数
         *
         * @param paramInterceptor
         * @return
         */
        public AppHttpSetting.Builder addInterceptor(ParamInterceptor paramInterceptor) {
            this.okHttpBuilder.addInterceptor(paramInterceptor);
            return this;
        }

        public AppHttpSetting.Builder addExceptionInterceptor(ExceptionInterceptor exceptionInterceptor) {
            this.okHttpBuilder.addInterceptor(exceptionInterceptor);
            return this;
        }

        public AppHttpSetting build() {
            return new AppHttpSetting(this);
        }

    }

}
